package com.cr.api.controller;

import com.alibaba.fastjson.JSONObject;
import com.cr.api.model.RegisterModel;
import com.cr.business.domain.CrUser;
import com.cr.business.service.ICrUserService;
import com.cr.common.core.controller.BaseController;
import com.cr.common.core.domain.AjaxResult;
import com.cr.common.utils.http.HttpUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Api(description = "微信登录相关接口")
/*    */
@RestController
/*    */
@RequestMapping({"/api/weixin"})
public class ApiWxLoginController extends BaseController {
    private static final String WX_GET_TOKEN = "https://api.weixin.qq.com/sns/oauth2/access_token";
    private static final String WX_GET_TOKEN_PARAM ="appid=wx41e9e2779d156f35&secret=56cafd1199f051c4643e68b65b256bab&code=CODE&grant_type=authorization_code";
    private static final String WX_GET_USERINFO = "https://api.weixin.qq.com/sns/userinfo";
    private static final String WX_GET_USERINFO_PARAM = "access_token=TOKEN&openid=OPENID";

    @Autowired
    private ICrUserService crUserService;

    @GetMapping({"/login/{code}"})
    @ApiOperation("微信登录")
    public AjaxResult wxlogin(@PathVariable String code) {
        String response = HttpUtils.sendGet(WX_GET_TOKEN,WX_GET_TOKEN_PARAM.replace("CODE",code));
        HashMap<String,String> map = JSONObject.parseObject(response, HashMap.class);
        String token = map.get("access_token");
        String openid = map.get("openid");
        String userInfo = HttpUtils.sendGet(WX_GET_USERINFO,WX_GET_USERINFO_PARAM.replace("TOKEN",token).replace("OPENID",openid));
        HashMap<String,String> userMap = JSONObject.parseObject(userInfo, HashMap.class);
        String nickname = userMap.get("nickname");
        String headimgurl = userMap.get("headimgurl");
        CrUser user = new CrUser();
        user.setOpenid(openid);
        List<CrUser> users = this.crUserService.selectCrUserList(user);
        if(CollectionUtils.isEmpty(users)){
            user.setLoginId(openid);
            user.setPassword("654321");
            user.setUserName(nickname);
            user.setHeadPortrait(headimgurl);
            user.setCreateTime(new Date());
            user.setCreateBy("system-wx");
            Integer i = Integer.valueOf(this.crUserService.insertCrUser(user));
            return AjaxResult.success(user);
        }
            return AjaxResult.success(users.get(0));
    }
}
